package net.ibizsys.eclipse.studio.xml;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import net.ibizsys.eclipse.studio.util.StringKit;

import org.w3c.dom.Node;

/**
 * 
 * @author <a href='http://www.weibo.com/xjtoo' target='_blank'>Enmaai</a>
 * @param <T>
 */
public abstract class XmlNodeList<T extends IBizSearchableNode> extends ArrayList<T>
{
	private static final long serialVersionUID = 1L;

	public static final String ATTR_ID = "ID";
	public static final String ATTR_NAME = "NAME";

	private Class<T> nodeClazz;
	private String id;
	private String name;

	@SuppressWarnings("unchecked")
	public XmlNodeList()
	{
		try
		{
			Type t = getClass().getGenericSuperclass();
			if (t instanceof ParameterizedType)
			{
				Type[] p = ((ParameterizedType) t).getActualTypeArguments();
				this.nodeClazz = (Class<T>) p[0];
			}
		} catch (Exception ex)
		{

		}
	}

	public void init(Node node)
	{
		init(node, null);
	}

	public void init(Node node, IBizProject project)
	{
		for (int i = 0; i < node.getAttributes().getLength(); i++)
		{
			Node attr = node.getAttributes().item(i);
			if (attr.getNodeType() == Node.TEXT_NODE)
			{
				continue;
			}
			initAttribute(attr.getNodeName(), attr.getNodeValue());
		}

		for (int i = 0; i < node.getChildNodes().getLength(); i++)
		{
			Node child = node.getChildNodes().item(i);
			if (child.getNodeType() == Node.TEXT_NODE)
			{
				continue;
			}
			initChildNode(child, project);
		}
	}

	/**
	 * 初始化属性
	 * 
	 * @param name
	 * @param value
	 */
	protected void initAttribute(String name, String value)
	{
		if (StringKit.IsEqual(ATTR_ID, name, true))
		{
			this.id = value;
			return;
		}
		if (StringKit.IsEqual(ATTR_NAME, name, true))
		{
			this.name = name;
			return;
		}
	}

	/**
	 * 初始化子节点
	 * 
	 * @param node
	 */
	protected void initChildNode(Node node, IBizProject project)
	{
		T child = createNode();

		if (child != null)
		{
			child.init(node, project);
			add(child);
		}
	}

	public String getId()
	{
		return id;
	}

	public String getName()
	{
		return name;
	}

	private T createNode()
	{
		if (this.nodeClazz != null)
		{
			try
			{
				return this.nodeClazz.newInstance();
			} catch (Exception ex)
			{
			}
		}
		return null;
	}

	public T getItemById(String id)
	{
		for (T entity : this)
		{
			if (StringKit.IsEqual(id, entity.getId(), true))
			{
				return entity;
			}
		}

		return null;
	}

	/**
	 * 是否匹配
	 * 
	 * @param keywords
	 * @return
	 */
	public List<T> match(String[] keywords)
	{
		List<T> list = new ArrayList<T>();

		for (T entity : this)
		{
			if (entity.match(keywords))
			{
				list.add(entity);
			}
		}

		return list;
	}

	/**
	 * 是否匹配
	 * 
	 * @param keyword
	 * @return
	 */
	public List<T> match(String keyword)
	{
		List<T> list = new ArrayList<T>();

		for (T entity : this)
		{
			if (entity.match(keyword))
			{
				list.add(entity);
			}
		}

		return list;
	}
}
